<template>
  <div class="goods-container">
    <!-- 顶部搜索和操作区 -->
    <div class="header-actions">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchKeyword"
            placeholder="输入商品名称搜索"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button @click="handleSearch">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-cascader
            v-model="selectedCategory"
            :options="categories"
            :props="cascaderProps"
            :loading="categoryLoading"
            placeholder="选择商品类目"
            clearable
            class="w-full"
          >
            <template #empty>
              <el-empty description="暂无分类数据" />
            </template>
          </el-cascader>
        </el-col>
        <el-col :span="14" class="text-right">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>新增商品
          </el-button>
          <el-button @click="handleRefresh">
            <el-icon><Refresh /></el-icon>刷新
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 表格容器 -->
    <div class="table-container">
      <el-table
        :data="goodsList"
        v-loading="loading"
        border
        stripe
        row-key="itemId"
        height="calc(100vh - 200px)"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="itemId" label="商品ID" width="100" sortable />
        <el-table-column label="商品图片" width="100">
          <template #default="{ row }">
            <el-image
              :src="row.image || '/default-image.png'"
              :preview-src-list="row.image ? [row.image] : []"
              fit="contain"
              class="product-image"
            >
              <template #error>
                <div class="image-placeholder">暂无图片</div>
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="商品名称" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="product-title">
              <span>{{ row.title || '暂无名称' }}</span>
              <el-tag v-if="row.sellPoint" size="small" class="ml-2">{{ row.sellPoint }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="商品价格" width="120" sortable>
          <template #default="{ row }">
            <span class="price">¥{{ ((row.price || 0) / 100).toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="num" label="库存" width="100" sortable>
          <template #default="{ row }">
            <el-tag :type="getStockTagType(row.num)">
              {{ row.num || 0 }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" width="180" sortable>
          <template #default="{ row }">
            {{ formatDate(row.updated) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" link @click="handleEdit(row)">
                <el-icon><Edit /></el-icon>编辑
              </el-button>
              <el-button type="success" link @click="handleStock(row)">
                <el-icon><Box /></el-icon>库存
              </el-button>
              <el-button
                type="warning"
                link
                @click="handleStatusToggle(row)"
              >
                {{ row.status === 1 ? '下架' : '上架' }}
              </el-button>
              <el-button type="danger" link @click="handleDelete(row)">
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页器 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 商品表单对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '新增商品' : '编辑商品'"
      v-model="dialogVisible"
      width="700px"
      destroy-on-close
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="formRef"
        label-width="100px"
        class="product-form"
      >
        <el-row :gutter="20">
          <el-col :span="14">
            <el-form-item label="商品名称" prop="title">
              <el-input v-model="form.title" maxlength="100" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="商品分类" prop="cid">
              <el-cascader
                v-model="form.cid"
                :options="categories"
                :props="cascaderProps"
                :loading="categoryLoading"
                placeholder="请选择商品分类"
                clearable
                class="w-full"
                :show-all-levels="true"
              >
                <template #empty>
                  <el-empty description="暂无分类数据" />
                </template>
              </el-cascader>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品价格" prop="price">
              <el-input-number
                v-model="form.price"
                :min="0"
                :precision="2"
                :step="0.1"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商品库存" prop="num">
              <el-input-number
                v-model="form.num"
                :min="0"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="商品卖点" prop="sellPoint">
          <el-input
            v-model="form.sellPoint"
            type="textarea"
            maxlength="500"
            show-word-limit
            rows="2"
          />
        </el-form-item>

        <el-form-item label="商品条码" prop="barcode">
          <el-input v-model="form.barcode" maxlength="30" />
        </el-form-item>

        <el-form-item label="商品图片">
          <el-upload
            class="product-upload"
            :action="'/logic/tools/upload'"
            :headers="uploadConfig.headers"
            :data="{ itemId: form.itemId }"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
          >
            <el-image
              v-if="form.image"
              :src="form.image"
              fit="contain"
              class="upload-image"
            />
            <div v-else class="upload-placeholder">
              <el-icon><Plus /></el-icon>
              <div class="upload-text">点击上传图片</div>
            </div>
          </el-upload>
        </el-form-item>

        <el-form-item label="商品状态">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="2"
            active-text="上架"
            inactive-text="下架"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 库存设置对话框 -->
    <el-dialog
      title="设置库存"
      v-model="stockDialogVisible"
      width="400px"
      destroy-on-close
    >
      <el-form :model="stockForm" label-width="100px">
        <el-form-item label="当前库存">
          <span class="current-stock">{{ currentStock }}</span>
        </el-form-item>
        <el-form-item label="库存数量">
          <el-input-number
            v-model="stockForm.num"
            :min="0"
            style="width: 200px"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="stockDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitStock" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import {
  Search, Plus, Refresh, Edit, Delete, Box
} from '@element-plus/icons-vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'

// 状态管理
const loading = ref(false)
const submitting = ref(false)
const goodsList = ref([])
const selectedRows = ref([])
const searchKeyword = ref('')
const selectedCategory = ref('')
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)

const categories = ref([])
const categoryLoading = ref(false)

// 转换分类数据为树形结构
const transformCategoryData = (data) => {
  // 创建一个映射表来存储所有分类
  const categoryMap = new Map()

  // 首先将所有分类添加到映射表中
  data.forEach(item => {
    categoryMap.set(item.categoryId, {
      value: item.categoryId,
      label: item.name,
      children: [],
      parent: item.parent,
      parentId: item.parentId,
      status: item.status
    })
  })

  // 构建树形结构
  const result = []
  categoryMap.forEach(category => {
    // 只处理状态正常(status=1)的分类
    if (category.status === 1) {
      if (category.parentId === 0) {
        // 顶级分类直接加入结果数组
        result.push(category)
      } else {
        // 将子分类添加到父分类的children数组中
        const parentCategory = categoryMap.get(category.parentId)
        if (parentCategory) {
          parentCategory.children.push(category)
        }
      }
    }
  })

  return result
}

// 获取分类数据
const getCategories = async () => {
  categoryLoading.value = true
  try {
    const res = await axios.get('/categories/all')
    if (Array.isArray(res.data)) {
      // 转换数据为树形结构
      categories.value = transformCategoryData(res.data)
    } else {
      ElMessage.error('获取分类数据失败')
      categories.value = []
    }
  } catch (error) {
    console.error('Error fetching categories:', error)
    ElMessage.error('获取分类数据失败')
    categories.value = []
  } finally {
    categoryLoading.value = false
  }
}

// Cascader配置
// const cascaderProps = {
//   value: 'value',
//   label: 'label',
//   children: 'children',
//   checkStrictly: true, // 允许选择任意一级
//   emitPath: true // 返回完整路径
// }

// 更新表单校验规则
const rules = {
  // ... 其他规则保持不变
  cid: [
    { required: true, message: '请选择商品分类', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (!value || value.length === 0) {
          callback(new Error('请选择商品分类'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

// 修改表单相关逻辑
const handleAdd = () => {
  dialogType.value = 'add'
  form.value = {
    title: '',
    price: 0,
    num: 0,
    image: '',
    status: 1,
    cid: [], // 初始化为空数组
    sellPoint: '',
    barcode: ''
  }
  dialogVisible.value = true
}

// 修改编辑商品逻辑
const handleEdit = (row) => {
  dialogType.value = 'edit'
  // 查找分类的完整路径
  const findCategoryPath = (categoryId) => {
    const path = []
    const findParent = (categories, targetId) => {
      for (const category of categories) {
        if (category.value === targetId) {
          path.unshift(category.value)
          return true
        }
        if (category.children && category.children.length > 0) {
          if (findParent(category.children, targetId)) {
            path.unshift(category.value)
            return true
          }
        }
      }
      return false
    }
    findParent(categories.value, categoryId)
    return path
  }

  form.value = {
    ...transformGoodsData(row),
    price: (row.price || 0) / 100,
    cid: findCategoryPath(row.cid) // 设置完整的分类路径
  }
  dialogVisible.value = true
}

// 表单提交前的数据处理
const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    // 获取选中分类的最后一个值作为实际的分类ID
    const categoryId = form.value.cid[form.value.cid.length - 1]

    const submitData = {
      ...form.value,
      price: Math.round(form.value.price * 100),
      cid: categoryId // 使用最终选择的分类ID
    }

    const config = {
      headers: {
        'Content-Type': 'application/json'
      }
    }

    if (dialogType.value === 'add') {
      await axios.post('/logic/item/upload', submitData, config)
      ElMessage.success('添加成功')
    } else {
      await axios.post('/logic/item/edit', submitData, config)
      ElMessage.success('编辑成功')
    }
    dialogVisible.value = false
    getGoodsList()
  } catch (error) {
    console.error('Form submission error:', error)
    ElMessage.error(dialogType.value === 'add' ? '添加失败' : '编辑失败')
  } finally {
    submitting.value = false
  }
}

// 在组件挂载时初始化分类数据
onMounted(async () => {
  await Promise.all([
    getGoodsList(),
    getCategories()
  ])
  await initTable()
  window.addEventListener('resize', handleResize)
})

// 表单状态
const dialogVisible = ref(false)
const dialogType = ref('add')
const form = ref({
  title: '',
  price: 0,
  num: 0,
  image: '',
  status: 1,
  cid: '',
  sellPoint: '',
  barcode: ''
})

// 上传配置
const uploadConfig = {
  headers: {
    // 如果需要添加额外的请求头在这里添加
  }
}

const formRef = ref(null)
// const rules = {
//   title: [
//     { required: true, message: '请输入商品名称', trigger: 'blur' },
//     { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
//   ],
//   price: [
//     { required: true, message: '请输入商品价格', trigger: 'blur' },
//     { type: 'number', min: 0, message: '价格必须大于等于0', trigger: 'blur' }
//   ],
//   num: [
//     { required: true, message: '请输入商品库存', trigger: 'blur' },
//     { type: 'number', min: 0, message: '库存必须大于等于0', trigger: 'blur' }
//   ],
//   cid: [
//     { required: true, message: '请选择商品分类', trigger: 'change' }
//   ]
// }

// 库存设置状态
const stockDialogVisible = ref(false)
const stockForm = ref({
  id: '',
  num: 0
})
const currentStock = ref(0)

// 数据转换函数
const transformGoodsData = (item) => {
  return {
    itemId: item.itemId || 0,
    title: item.title || '暂无名称',
    sellPoint: item.sellPoint || '',
    price: item.price || 0,
    num: item.num || 0,
    barcode: item.barcode || '',
    image: item.image || '',
    cid: item.cid || null,
    status: item.status || 2,
    created: item.created || '',
    updated: item.updated || ''
  }
}

// 获取商品列表
const getGoodsList = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      keyword: searchKeyword.value,
      categoryId: selectedCategory.value
    }

    const res = await axios.get('/logic/item/list', { params })
    console.log('API Response:', res.data)

    if (Array.isArray(res.data)) {
      goodsList.value = res.data.map(transformGoodsData)
      total.value = res.data.length
    } else if (res.data && Array.isArray(res.data.data)) {
      goodsList.value = res.data.data.map(transformGoodsData)
      total.value = res.data.total || res.data.data.length
    } else {
      goodsList.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('Error fetching goods list:', error)
    ElMessage.error('获取商品列表失败')
    goodsList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 表格选择事件
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 搜索和刷新
const handleSearch = () => {
  pageNum.value = 1
  getGoodsList()
}

const handleRefresh = () => {
  searchKeyword.value = ''
  selectedCategory.value = ''
  handleSearch()
}

// 分页事件
const handleSizeChange = (val) => {
  pageSize.value = val
  getGoodsList()
}

const handleCurrentChange = (val) => {
  pageNum.value = val
  getGoodsList()
}

// 表单提交
// const submitForm = async () => {
//   if (!formRef.value) return
//
//   try {
//     await formRef.value.validate()
//     submitting.value = true
//
//     const submitData = {
//       ...form.value,
//       price: Math.round(form.value.price * 100)
//     }
//
//     const config = {
//       headers: {
//         'Content-Type': 'application/json'
//       }
//     }
//
//     if (dialogType.value === 'add') {
//       await axios.post('/logic/item/upload', submitData, config)
//       ElMessage.success('添加成功')
//     } else {
//       await axios.post('/logic/item/edit', submitData, config)
//       ElMessage.success('编辑成功')
//     }
//     dialogVisible.value = false
//     getGoodsList()
//   } catch (error) {
//     console.error('Form submission error:', error)
//     ElMessage.error(dialogType.value === 'add' ? '添加失败' : '编辑失败')
//   } finally {
//     submitting.value = false
//   }
// }

// 图片上传相关
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleUploadSuccess = async (res) => {
  try {
    if (res.code === 200) {
      // 使用完整的 MinIO 文件地址
      form.value.image = `/logic/tools/download?fileName=${res.msg}&path=pic`
      ElMessage.success('上传成功')
    } else {
      ElMessage.error('上传失败：' + (res.msg || '未知错误'))
    }
  } catch (error) {
    console.error('Upload error:', error)
    ElMessage.error('上传失败：' + (error.message || '未知错误'))
  }
}

const handleUploadError = (error) => {
  console.error('Upload error:', error)
  ElMessage.error('上传失败：' + (error.message || '未知错误'))
}

// 新增商品
// const handleAdd = () => {
//   dialogType.value = 'add'
//   form.value = {
//     title: '',
//     price: 0,
//     num: 0,
//     image: '',
//     status: 1,
//     cid: '',
//     sellPoint: '',
//     barcode: ''
//   }
//   dialogVisible.value = true
// }

// 编辑商品
// const handleEdit = (row) => {
//   dialogType.value = 'edit'
//   form.value = {
//     ...transformGoodsData(row),
//     price: (row.price || 0) / 100
//   }
//   dialogVisible.value = true
// }

// 删除商品
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该商品？', '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })

    const response = await axios.delete(`/logic/item/delete/${row.itemId}`, {
      headers: {
        'Content-Type': 'application/json'
      }
    })

    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      getGoodsList()
    } else {
      ElMessage.error(response.data.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Delete error:', error.response?.data || error)
      ElMessage.error('删除失败')
    }
  }
}

// 切换商品状态
const handleStatusToggle = async (row) => {
  try {
    const newStatus = row.status === 1 ? 2 : 1
    await axios.post('/logic/item/edit',
      {
        ...row,
        status: newStatus
      },
      {
        headers: {
          'Content-Type': 'application/json'
        }
      }
    )
    ElMessage.success(newStatus === 1 ? '商品已上架' : '商品已下架')
    row.status = newStatus
  } catch (error) {
    console.error('Status toggle error:', error)
    ElMessage.error('操作失败')
  }
}

// 设置库存
const handleStock = (row) => {
  stockForm.value = {
    itemId: row.itemId,
    num: row.num || 0
  }
  currentStock.value = row.num || 0
  stockDialogVisible.value = true
}

// 提交库存设置
const submitStock = async () => {
  submitting.value = true
  try {
    await axios.post('/logic/item/setStock', null, {
      params: {
        id: stockForm.value.itemId,
        num: String(stockForm.value.num)
      }
    })
    ElMessage.success('设置成功')
    stockDialogVisible.value = false
    getGoodsList()
  } catch (error) {
    console.error('Stock update error:', error)
    ElMessage.error('设置失败')
  } finally {
    submitting.value = false
  }
}

// 状态相关工具函数
const getStatusType = (status) => {
  const types = {
    1: 'success',
    2: 'info',
    3: 'danger'
  }
  return types[status || 2] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    1: '上架',
    2: '下架',
    3: '已删除'
  }
  return texts[status || 2] || '未知'
}

// 库存标签类型
const getStockTagType = (num) => {
  num = parseInt(num) || 0
  if (num > 10) return 'success'
  if (num > 0) return 'warning'
  return 'danger'
}

// 格式化日期
const formatDate = (date) => {
  return date ? dayjs(date).format('YYYY-MM-DD HH:mm:ss') : '--'
}

// 表格初始化
const initTable = async () => {
  await nextTick()
  const bodyWrapper = document.querySelector('.el-table__body-wrapper')
  if (bodyWrapper) {
    bodyWrapper.style.height = 'calc(100vh - 200px)'
  }
}

// 窗口大小改变处理
const handleResize = () => {
  initTable()
}

// 生命周期钩子
onMounted(async () => {
  await getGoodsList()
  await initTable()
  window.addEventListener('resize', handleResize)

  // 添加样式来抑制警告
  const style = document.createElement('style')
  style.innerHTML = `
    .el-table__body {
      will-change: transform;
    }
  `
  document.head.appendChild(style)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.goods-container {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
  box-sizing: border-box;
}

.header-actions {
  margin-bottom: 20px;
}

.table-container {
  position: relative;
  flex: 1;
}

.el-table {
  --el-table-border-color: var(--el-border-color-lighter);
  will-change: transform;
}

.pagination-container {
  position: sticky;
  bottom: 0;
  margin-top: 20px;
  padding: 10px 0;
  background: #fff;
  border-top: 1px solid var(--el-border-color-lighter);
  display: flex;
  justify-content: flex-end;
  z-index: 10;
}

.text-right {
  text-align: right;
}

.product-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  object-fit: cover;
}

.image-placeholder {
  width: 60px;
  height: 60px;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 12px;
  border-radius: 4px;
}

.product-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

.product-form {
  padding: 20px;
}

.product-upload {
  width: 200px;
  height: 200px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.product-upload:hover {
  border-color: #409eff;
}

.upload-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #8c939d;
}

.upload-text {
  margin-top: 8px;
  font-size: 12px;
}

.current-stock {
  font-size: 24px;
  color: #409eff;
  font-weight: bold;
}

.ml-2 {
  margin-left: 8px;
}
</style>
